package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.RemarksMapper;
import aiku.numericalcontroloa.Model.Dto.DieCustomDto;
import aiku.numericalcontroloa.Model.Entity.Remarks;
import aiku.numericalcontroloa.Model.Vo.DieCustomVo;
import aiku.numericalcontroloa.Model.Vo.ExpenseVo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aiku.numericalcontroloa.Model.Entity.DieCustom;
import aiku.numericalcontroloa.Model.Entity.DieOrder;
import aiku.numericalcontroloa.Service.DieCustomService;
import aiku.numericalcontroloa.Mapper.DieCustomMapper;
import aiku.numericalcontroloa.Mapper.DieOrderMapper;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 马
 * @description 针对表【die_custom】的数据库操作Service实现
 * @createDate 2024-05-17 17:09:22
 */
@Service
public class DieCustomServiceImpl extends ServiceImpl<DieCustomMapper, DieCustom>
        implements DieCustomService {
    /**
     * 添加客户
     * 
     * @param dieCustom
     * @return
     */
    @Autowired
    private DieCustomMapper dieCustomMapper;

    @Autowired
    private RemarksMapper remarksMapper;

    @Autowired
    private DieOrderMapper dieOrderMapper;

    /**
     * 新增客户
     * 
     * @param dieCustomDto
     * @return
     */
    @Override
    @Transactional
    public Result addCustom(DieCustomDto dieCustomDto) {
        if (dieCustomDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        DieCustom dieCustom = new DieCustom();
        // 设置公司名
        if (dieCustomDto.getCompany() != null) {
            dieCustom.setCompany(dieCustomDto.getCompany());
        }
        // 设置客户名
        if (dieCustomDto.getCustomName() == null || dieCustomDto.getCustomName().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        dieCustom.setCustomName(dieCustomDto.getCustomName());
        // 设置电话
        if (dieCustomDto.getPhone() == null || dieCustomDto.getPhone().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        dieCustom.setPhone(dieCustomDto.getPhone());
        // 设置地址
        if (dieCustomDto.getAddress() == null || dieCustomDto.getAddress().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        dieCustom.setAddress(dieCustomDto.getAddress());
        // 设置做板要求
        if (dieCustomDto.getDemand() != null) {
            dieCustom.setDemand(dieCustomDto.getDemand());
        }
        // 保存数据
        dieCustomMapper.insert(dieCustom);

        // 设置备注
        if (dieCustomDto.getRemark() != null) {
            Remarks remarks = new Remarks();
            remarks.setQueryId(dieCustom.getId());
            remarks.setRemarkContent(dieCustomDto.getRemark());
            remarksMapper.insert(remarks);
        }

        return Result.success("添加成功");
    }

    /**
     * 通过昵称模糊查询客户信息
     * 
     * @param name
     * @return
     */
    @Override
    public Result selectCustomByNickName(String name) {
        LambdaQueryWrapper<DieCustom> queryWrapper = new LambdaQueryWrapper<DieCustom>().like(DieCustom::getCustomName,
                name);
        return Result.success(dieCustomMapper.selectList(queryWrapper));
    }

    /**
     * 分页查询客户信息
     * 
     * @param page
     * @param size
     * @return
     */
    @Override
    public Result selectCustomByPage(Long page, Long size) {
        Page<DieCustom> customPage = new Page<>(page, size);
        List<DieCustom> dieCustomList = dieCustomMapper.selectPage(customPage, null).getRecords();
        Long count = dieCustomMapper.selectCount(null);
        DieCustomVo customVo = new DieCustomVo();
        customVo.setDieCustomList(dieCustomList);
        customVo.setTotal(count);
        return Result.success(customVo);
    }

    @Override
    public Result getCustomList(DieCustomDto dieCustomDto) {
        if (dieCustomDto == null || (dieCustomDto.getCurrentPage() == null || dieCustomDto.getPageSize() == null)) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Page<DieCustom> dieCustomPage = new Page<>(dieCustomDto.getCurrentPage(), dieCustomDto.getPageSize());
        // 条件查询
        LambdaQueryWrapper<DieCustom> dieCustomLQW = new LambdaQueryWrapper<>();
        dieCustomLQW.orderByDesc(DieCustom::getCreateTime);
        // 根据公司名、客户名、联系电话、地址查询
        if (dieCustomDto.getCompany() != null) {
            dieCustomLQW.and(d -> d.like(DieCustom::getCompany, dieCustomDto.getCompany())
                    .or().like(DieCustom::getCustomName, dieCustomDto.getCompany())
                    .or().like(DieCustom::getPhone, dieCustomDto.getCompany())
                    .or().like(DieCustom::getAddress, dieCustomDto.getCompany()));
        }
        List<DieCustom> dieCustomList = dieCustomMapper.selectList(dieCustomLQW);
        List<DieCustomDto> dieCustomDtoList = new ArrayList<>();
        if (!dieCustomList.isEmpty()) {
            // 根据id查询备注
            List<String> customIdList = dieCustomList.stream().map(DieCustom::getId).collect(Collectors.toList());
            LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
            remarksLQW.in(Remarks::getQueryId, customIdList);
            List<Remarks> remarksList = remarksMapper.selectList(remarksLQW);
            // 将List集合处理成map集合，方便获取对象
            Map<String, Remarks> remarksMap = remarksList.stream()
                    .collect(Collectors.toMap(Remarks::getQueryId, r -> remarksList.stream()
                            .filter(item -> item.getQueryId().equals(r.getQueryId()))
                            .findFirst()
                            .orElse(null)));
            for (DieCustom dieCustom : dieCustomList) {
                DieCustomDto dieCustomDto1 = new DieCustomDto();
                BeanUtils.copyProperties(dieCustom, dieCustomDto1);
                if (remarksMap.containsKey(dieCustom.getId())) {
                    dieCustomDto1.setRemark(remarksMap.get(dieCustom.getId()).getRemarkContent());
                }
                dieCustomDtoList.add(dieCustomDto1);
            }
        }

        for (DieCustomDto item : dieCustomDtoList) {
            LambdaQueryWrapper<DieOrder> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(DieOrder::getNameId, item.getId()).eq(DieOrder::getReceivables, 0)
//                    .ne(DieOrder::getCompleteOrder, "");
            queryWrapper.eq(DieOrder::getNameId, item.getId()).eq(DieOrder::getReceivables, 0);
            Long count = dieOrderMapper.selectCount(queryWrapper);
            item.setNoreceivables(count);
        }
        List<DieCustomDto> dieCustomDtos = new ArrayList();
        for (DieCustomDto item : dieCustomDtoList) {
            LambdaQueryWrapper<DieOrder> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(DieOrder::getNameId, item.getId()).eq(DieOrder::getReceivables, 0)
//                    .ne(DieOrder::getCompleteOrder, "");
            queryWrapper.eq(DieOrder::getNameId, item.getId()).eq(DieOrder::getReceivables, 0);
//            item.setTotalAmount(dieOrderMapper.selectList(queryWrapper).stream().map(DieOrder::getPrice)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add));
            item.setTotalAmount(dieOrderMapper.selectList(queryWrapper).stream()
                    .map(DieOrder::getPrice)
                    .filter(Objects::nonNull) // 过滤掉 null 的价格
                    .reduce(BigDecimal.ZERO, BigDecimal::add));
            insertInDescendingOrder(dieCustomDtos, item);
        }

        dieCustomDtoList = dieCustomDtos;

        switch (dieCustomDto.getSelect()) {
            case 1:
                dieCustomDtoList = dieCustomDtoList.stream()
                        .sorted(Comparator.comparing(DieCustomDto::getNoreceivables)).collect(Collectors.toList());
                break;
            case 2:
                dieCustomDtoList = dieCustomDtoList.stream()
                        .sorted(Comparator.comparing(DieCustomDto::getNoreceivables).reversed())
                        .collect(Collectors.toList());
                break;
            case 3:
                dieCustomDtoList = dieCustomDtoList.stream()
                        .sorted(Comparator.comparing(DieCustomDto::getTotalAmount)).collect(Collectors.toList());
                break;
            case 4:
                dieCustomDtoList = dieCustomDtoList.stream()
                        .sorted(Comparator.comparing(DieCustomDto::getTotalAmount).reversed())
                        .collect(Collectors.toList());
                break;
            case 5:
                // 1. 先查询所有订单并按创建时间倒序排序
                QueryWrapper<DieOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.orderByDesc("create_time");
                List<DieOrder> dieOrderList = dieOrderMapper.selectList(queryWrapper);
                dieOrderList = dieOrderList.stream()
                        .sorted(Comparator.comparing(DieOrder::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())))
                        .collect(Collectors.toList());
                
                // 2. 创建新的列表存储排序后的dieCustomDto
                List<DieCustomDto> sortedDieCustomDtoList = new ArrayList<>();
                
                // 3. 按照订单创建时间的顺序查找对应的客户
                for (DieOrder order : dieOrderList) {
                    dieCustomDtoList.stream()
                            .filter(dto -> dto.getId().equals(order.getNameId()))
                            .findFirst()
                            .ifPresent(sortedDieCustomDtoList::add);
                }
                
                // 4. 用排序后的列表替换原列表
                dieCustomDtoList = sortedDieCustomDtoList;
                break;
        }

        // 按月份对客户列表进行分组
        Map<Integer, List<DieCustomDto>> monthlyCustomers = new HashMap<>();
        // 初始化12个月的列表
        for (int i = 1; i <= 12; i++) {
            monthlyCustomers.put(i, new ArrayList<>());
        }

        // 获取所有客户的订单
        for (DieCustomDto customer : dieCustomDtoList) {
            LambdaQueryWrapper<DieOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DieOrder::getNameId, customer.getId())
                       .eq(DieOrder::getReceivables, 0);
            
            List<DieOrder> orders = dieOrderMapper.selectList(queryWrapper);
            
            // 获取该客户最早的订单时间所在月份
            Optional<Date> earliestOrderDate = orders.stream()
                .map(DieOrder::getCreateTime)
                .filter(Objects::nonNull)
                .min(Date::compareTo);
                
            if (earliestOrderDate.isPresent()) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(earliestOrderDate.get());
                int month = cal.get(Calendar.MONTH) + 1; // 获取月份(1-12)
                monthlyCustomers.get(month).add(customer);
            }
        }

        int listLength = dieCustomDtoList.size();
        int selectPageStart = (int) ((dieCustomPage.getCurrent() - 1) * dieCustomPage.getSize());
        int selectPageEnd = (int) (dieCustomPage.getCurrent() * dieCustomPage.getSize());
        if (selectPageEnd > listLength) {
            selectPageEnd = listLength;
        }
        dieCustomDtoList = dieCustomDtoList.subList(selectPageStart, selectPageEnd);

        Map<String, Object> map = new HashMap<>();
        map.put("total", listLength);
        map.put("dieCustomDtoList", dieCustomDtoList);
        map.put("monthlyData", monthlyCustomers);  // 添加按月份分组的数据
        return Result.success("查询成功", map);
    }

    @Override
    @Transactional
    public Result updateCustom(DieCustomDto dieCustomDto) {
        if (dieCustomDto == null || dieCustomDto.getId() == null || dieCustomDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询是否有该客户
        DieCustom dieCustom = dieCustomMapper.selectById(dieCustomDto.getId());
        if (dieCustom == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        BeanUtils.copyProperties(dieCustomDto, dieCustom);
        dieCustomMapper.updateById(dieCustom);
        // 更新备注
        if (dieCustomDto.getRemark() != null) {
            LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
            remarksLQW.eq(Remarks::getQueryId, dieCustom.getId());
            Remarks remarks = remarksMapper.selectOne(remarksLQW);
            if (remarks == null) {
                remarks = new Remarks();
                remarks.setQueryId(dieCustom.getId());
                remarks.setRemarkContent(dieCustomDto.getRemark());
                remarksMapper.insert(remarks);
            } else {
                remarks.setRemarkContent(dieCustomDto.getRemark());
                remarksMapper.updateById(remarks);
            }
        }
        return Result.success("修改成功");
    }

    private static void insertInDescendingOrder(List<DieCustomDto> list, DieCustomDto item) {
        // 找到插入位置，保持列表按数量倒序
        int i;
        for (i = 0; i < list.size(); i++) {
            if (item.getNoreceivables() > list.get(i).getNoreceivables()) {
                break;
            }
        }
        // 插入到找到的位置
        list.add(i, item);
    }

}
